


//
//  OauthController.swift
//  mywei
//
//  Created by myd on 15/12/16.
//  Copyright © 2015年 myd1. All rights reserved.
//

import UIKit
import SVProgressHUD


class OauthController: UIViewController {

    
    override func loadView() {
        view = webview
        webview.delegate = self
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        navigationItem.rightBarButtonItem=UIBarButtonItem(title: "填充", style: UIBarButtonItemStyle.Plain, target: self, action: "autofill")
        let request = NSURLRequest(URL:OauthNetwork.sharedinstance.oauth())
        webview .loadRequest(request)
        
    }
func close()
{
    SVProgressHUD.dismiss()
   dismissViewControllerAnimated(true, completion: nil)
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    func autofill()
    {
        let js = "document.getElementById('userId').value='18502804975';" + "document.getElementById('passwd').value='love123';"
        webview .stringByEvaluatingJavaScriptFromString(js)
    }
   private lazy var webview = UIWebView()
}

extension OauthController : UIWebViewDelegate
{
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
    
    }
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD .dismiss()
    }
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.showWithStatus("正在加载",maskType: SVProgressHUDMaskType.Black)
        
    }
    
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {

        let  url = request.URL!.absoluteString
        if !url.hasPrefix(OauthNetwork.sharedinstance.redirect_uri)
        {
            return true
        }
        if  let query = request.URL?.query{
            let keyword = "code="
            if query.hasPrefix(keyword)
            {
                let nscode = query as NSString
                let code = nscode.substringFromIndex(keyword.characters.count)
                loadmessage(code)
            }else{
                print("信息错误")
                self.close()}
        }
        return false
    }
    
    
    
    func loadmessage(code : String)
    {
   OauthNetwork.sharedinstance.loadcode(code) { (resuit, error) -> () in
   if resuit == nil || error != nil
   {
   self.showerror("网络错误")
    self.close()
    return
    }
    let users = user1(dict : resuit!)
    users.saveaccess_token()
    
    let win = UIApplication.sharedApplication().keyWindow
    win?.login()
  
        }}
    
    private func showerror(error : String)
    {
   SVProgressHUD.showErrorWithStatus(error)
        
      
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW,(Int64)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
            self.close()
        })
    }
    }
    

